<script setup lang="ts">
  import { h, ref, watch } from 'vue';
  import { useRoute } from 'vue-router';
  import SvgIcon from '@/components/svgIcon/index.vue';
  import { pageStore, useAppStore } from '@/store';
  import { getdirList, deleteDir, moveDir } from '@/api/dashboard';
  import useLoading from '@/hooks/loading';
  import { collectAllKeys, deepTree } from '@/utils/utils';
  import Edit from './edit/index.vue';
  import Share from './share/index.vue';
  import Guidang from './guidang/index.vue';
  const appStore = useAppStore();
  const pageStore = usePageStore();
  import Move from './move/index.vue';
  const route = useRoute();
  const contextMenu = defineAsyncComponent(
    () => import('@/components/right-click-menu/index.vue')
  );
  import Add from './add/index.vue';
  import { Message, Modal } from '@arco-design/web-vue';
  import usePageStore from '@/store/modules/page';
  const type = ref<number>();
  const visible = ref(false);
  const visible1 = ref(false);
  const visible2 = ref(false);
  const visible3 = ref(false);
  const visible4 = ref(false);
  const { loading, setLoading } = useLoading(false);
  const contextMenuRef = ref();
  const sonFormType = ref<any>();
  const treeData = ref();
  const treeData1 = ref();
  const currentParams = ref<any>();
  const allExpandedKeys = ref([]);
  const expandedKeys = ref([]);
  // 路由监听配置 - 展开二级目录（文件夹操作）
  const targetPaths = ['/files/personal', '/files/public', '/files/archive'];
  const currentTarget = ref();

  // 目录请求
  const fetchData = async () => {
    loading.value = true;
    const path = route.path;
    if (targetPaths.includes(path)) {
      type.value = path.includes('public')
        ? 1
        : path.includes('personal')
        ? 2
        : 3;
      // 设置默认type
      pageStore.setCurrentDirType(type.value);
      const res = await getdirList({ dir_type: type.value });
      treeData.value = deepTree(
        'dir_name',
        res.data,
        'dir_id',
        'dir_id',
        'Files'
      );
      treeData.value.unshift({
        title: '顶级菜单',
        key: 0,
        id: 0,
      });
      treeData1.value = deepTree(
        'dir_name',
        res.data,
        'dir_id',
        'dir_id',
        'Files'
      );
      const dirId = treeData1.value[0]?.id ? treeData1.value[0].id : null;
      pageStore.setCurrentDocDirId(dirId);
      // 初始化展开
      allExpandedKeys.value = collectAllKeys(treeData1.value);
      expandedKeys.value = [];
      sonFormType.value = [
        {
          name: 'dir_pid',
          label: '上级目录',
          type: 'a-tree-select',
          fieldProps: {
            span: 24,
            placeholder: '默认为顶级目录',
            data: treeData.value ? treeData.value : [],
          },
        },
        {
          name: 'dir_name',
          label: '目录名称',
          type: 'a-input',
          fieldProps: {
            span: 24,
          },
          rules: [
            {
              required: true,
              message: '请输入',
            },
          ],
        },

        {
          name: 'dir_sort',
          label: '排序',
          type: 'a-input-number',
          extra: '排序号越大目录就越靠前',
          fieldProps: {
            span: 24,
          },
        },
      ];
      loading.value = false;
    }
  };

  // 路由变化监听
  watch(
    () => route.path,
    () => {
      fetchData();
    },
    { immediate: true }
  ); // 初始加载时执行

  // 事件处理方法
  const showContextMenu = (e: MouseEvent) => {
    contextMenuRef.value?.show(e);
  };

  function displayRightMenu(e: any) {
    e.preventDefault();
    const { __vueParentComponent: vueParentComponent } = e.target;
    showContextMenu(e);
    currentTarget.value = vueParentComponent;
  }

  const handleRefresh = () => {
    loading.value = true;
    fetchData();
    loading.value = false;
  };

  const handleMenuSelect = (item: any) => {
    const dir_id = currentTarget.value.attrs.id;
    const title = currentTarget.value.props.title;
    switch (item.label) {
      case '删除目录':
        Modal.confirm({
          title: '系统提示',
          content: '确定要删除选中的文档吗吗？',
          okText: '确定',
          cancelText: '取消',
          onOk: () => {
            return new Promise((resolve, reject) => {
              deleteDir({
                dir_ids: [dir_id],
              })
                .then((res) => {
                  if (res?.code == 200) {
                    loading.value = true;
                    Message.success('删除成功！');
                    resolve(true);
                    fetchData();
                  } else {
                    reject();
                  }
                })
                .catch(() => {
                  Message.error('删除失败');
                  reject();
                })
                .finally(() => {
                  loading.value = false;
                });
            });
          },
        });
        break;
      case '新增目录':
        visible.value = true;
        currentParams.value = {
          type: type, // 当前目录类型
          id: dir_id,
        };
        break;
      case '编辑目录':
        visible1.value = true;
        currentParams.value = {
          type: type, // 当前目录类型
          id: dir_id,
        };
        break;
      case '文件夹移动':
        visible2.value = true;
        currentParams.value = {
          id: dir_id, //要移动的目录id
          title: title,
        };
        break;
      case '文件夹归档':
        visible3.value = true;
        currentParams.value = {
          id: dir_id, //要移动的目录id
          title: title,
        };
        break;
      case '文件夹共享':
        visible4.value = true;
        currentParams.value = {
          id: dir_id, //要移动的目录id
          title: title,
        };
        break;
    }
  };

  const moveDirRequest = async (params: {
    dir_id: number;
    to_dir_id: number;
  }) => {
    try {
      await moveDir(params);
      Message.success('目录移动成功！');
      handleRefresh();
    } catch (error) {
      Message.error('目录移动失败：' + (error as Error).message);
      // 可选：回滚树结构（需要保存原数据）
      // treeData.value = JSON.parse(JSON.stringify(originalTreeData.value));
    }
  };

  function onDrop({ dragNode, dropNode, dropPosition }: any) {
    // 本地树结构更新（原有逻辑）
    const data = treeData.value;
    const loop = (
      data: any[],
      key: string,
      callback: (item: any, index: number, arr: any[]) => void
    ) => {
      data.some((item, index, arr) => {
        if (item.key === key) {
          callback(item, index, arr);
          return true;
        }
        if (item.children) {
          return loop(item.children, key, callback);
        }
        return false;
      });
    };

    loop(data, dragNode.key, (_, index, arr) => {
      arr.splice(index, 1);
    });

    if (dropPosition === 0) {
      loop(data, dropNode.key, (item) => {
        item.children = item.children || [];
        item.children.push(dragNode);
      });
    } else {
      loop(data, dropNode.key, (_, index, arr) => {
        arr.splice(dropPosition < 0 ? index : index + 1, 0, dragNode);
      });
    }

    // 接口参数处理
    const dirId = Number(dragNode.key);
    let toDirId = 0;

    if (dropNode) {
      if (dropPosition === 0) {
        toDirId = Number(dropNode.key);
      } else {
        toDirId = getParentDirId(dropNode);
      }
    }

    // 调用接口
    moveDirRequest({ dir_id: dirId, to_dir_id: toDirId });
  }

  const getParentDirId = (
    node: any,
    parentId = 0,
    visited = new Set()
  ): number => {
    if (visited.has(node)) return parentId;
    visited.add(node);

    if (node.parent) {
      return getParentDirId(node.parent, Number(node.parent.key), visited);
    }
    return parentId;
  };
  function toggleExpanded() {
    expandedKeys.value = expandedKeys?.value.length
      ? []
      : allExpandedKeys.value;
  }

  function handleselect(selectedKeys: any, data: any) {
    pageStore.setCurrentDocDirId(selectedKeys[0]);
  }
</script>

<template>
  <div class="menu2">
    <a-card
      title="目录"
      style="height: 100%"
      :bordered="false"
      :loading="loading"
    >
      <template #extra>
        <div style="display: flex; flex-direction: row; align-items: center">
          <a-tooltip content="添加目录">
            <div
              style="cursor: pointer"
              @click="
                () => {
                  visible = true;
                  currentParams = {
                    type: type, // 当前目录类型
                  };
                }
              "
            >
              <a-button type="text" size="mini">
                <template #icon>
                  <icon-plus-circle-fill />
                </template>
              </a-button>
            </div>
          </a-tooltip>
          <a-tooltip
            :content="expandedKeys.length === 0 ? '展开目录' : '折叠目录'"
          >
            <div>
              <a-button type="text" size="mini" @click="toggleExpanded">
                <template #icon>
                  <icon-expand v-if="expandedKeys.length === 0" />
                  <icon-shrink v-else />
                </template>
              </a-button>
            </div>
          </a-tooltip>
        </div>
      </template>
      <a-tree
        draggable
        blockNode
        v-if="!loading"
        :default-selected-keys="[pageStore.dirId]"
        :data="treeData1"
        show-line
        @select="handleselect"
        @contextmenu="displayRightMenu"
        @drop="onDrop"
        v-model:expanded-keys="expandedKeys"
      >
        <template #icon>
          <svg-icon class="icon" name="Files" />
        </template>
      </a-tree>
    </a-card>
  </div>
  <contextMenu
    ref="contextMenuRef"
    :menu-items="appStore.fileMethods[1]"
    @select="handleMenuSelect"
  />
  <Add
    v-if="visible"
    v-model:visible="visible"
    :form-type="sonFormType"
    :params="currentParams"
    @refresh="handleRefresh"
  />
  <Edit
    v-if="visible1"
    v-model:visible="visible1"
    :form-type="sonFormType"
    :params="currentParams"
    @refresh="handleRefresh"
  />
  <Move
    v-if="visible2"
    v-model:visible="visible2"
    :data="treeData1"
    :params="currentParams"
    @refresh="handleRefresh"
  />
  <Guidang
    v-if="visible3"
    v-model:visible="visible3"
    :params="currentParams"
    @refresh="handleRefresh"
  />
  <Share
    v-if="visible4"
    v-model:visible="visible4"
    :params="currentParams"
    @refresh="handleRefresh"
  />
</template>

<style scoped lang="less">
  .menu2 {
    height: 100%;
    box-sizing: border-box;
    padding: 10px;
    cursor: default !important;
    background: #f7f8fa;
    overflow-x: hidden;
  }
  :deep(.icon) {
    width: 1.2em !important;
    height: 1.2em !important;
  }

  :deep(.arco-tree-node-title-text) {
    font-size: 12px;
    width: 140px;
    overflow: hidden; /* 隐藏溢出内容 */
    white-space: nowrap; /* 禁止换行 */
    text-overflow: ellipsis; /* 显示省略号 */
  }

  :deep(.arco-tree-node-indent-block) {
    width: 0px !important;
  }

  :deep(.arco-tree-node-indent) {
  }
</style>
